import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

public class Food extends Actor {    
    int x, y;
    
    // 创建一个数组存储五个子类对象
    public static Class[] foodClasses = {Food0.class, Food1.class,Food2.class,Food3.class};

    // 更新食物位置
    public void act() {
        setFood();
    }

    public void setFood() {
        
    }
    public void randomChose()
    {
        if (isTouching(Snake.class)) {  // 如果碰到贪食蛇
            // 获取当前世界
            World world = getWorld();

            // 移除所有Food对象（包括所有子类对象）
            for (Object obj : world.getObjects(Food.class)) {
                world.removeObject((Actor) obj);
            }

            // 随机选择一个Food子类
            Class selectedFoodClass = foodClasses[Greenfoot.getRandomNumber(foodClasses.length)];
            
            try {
                // 创建一个随机选择的Food子类的实例
                Food newFood = (Food) selectedFoodClass.getDeclaredConstructor().newInstance();
                // 随机位置
                
                x = 10+Greenfoot.getRandomNumber(world.getWidth()-20);
                y = 10+Greenfoot.getRandomNumber(world.getHeight()-20);
                
                // 将新食物添加到世界中
                world.addObject(newFood, x, y);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
